#include "ItemController.h"
#include"dbconnect/Model.h"
#include"dbconnect/DBDao.h"
#include"ServerMaster.h"
#include"DBMaster.h"

using namespace DBModel;

ItemController::ItemController(Object* master)
{
	m_master = master;
}

ItemController::~ItemController()
{
}

int ItemController::addItem(const int& userId, const int& id, const int& size)
{
	auto master = dynamic_cast<ServerMaster*>(m_master);
	Items item;
	item.id = id;
	DBDao<Items> dao(master->getDBMaster()->getSqlConnnect());
	dao.setModel(item);
	auto list = dao.queryModel();
	if (list.size() == 1)
	{
		int newNum = size + list[0].nums;
		item.nums = newNum;
		dao.setModel(item);
		return dao.updateModel("id", id) ? 1 : 0;
	}
	else
	{
		item.nums = size;
		dao.setModel(item);
		return dao.insertModel() ? 1 : 0;
	}
}

int ItemController::useItem(const int& userId, const int& id, const int& size)
{
	auto master = dynamic_cast<ServerMaster*>(m_master);
	Items item;
	item.id = id;
	item.userId = userId;
	DBDao<Items> dao(master->getDBMaster()->getSqlConnnect());
	dao.setModel(item);
	auto list = dao.queryModel();
	if (list.size() == 1)
	{
		int haveNum = list[0].nums;
		if (haveNum >= size)
		{
			int newNum = haveNum - size;
			if (newNum > 0)
			{
				item.nums = newNum;
				dao.setModel(item);
				std::string condition = "";
				condition.append("id=");
				condition.append(std::to_string(id));
				condition.append(" and userId=");
				condition.append(std::to_string(userId));
				return dao.updateModel(condition) ? 1 : 0;
			}
			else
			{
				dao.setModel(item);
				return dao.deleteModel() ? 1 : 0;
			}
		}
		else
		{
			return 0;
		}
	}
	else
	{
		return 0;
	}
}
